#include "../include/ThreadPool.h"
#include <unistd.h>

namespace myNameSpace {
ThreadPool::ThreadPool(size_t threadsNum, size_t queueSize): _threads(), _threadsNum(threadsNum), _taskQueue(queueSize), _isExit(false) {
    _threads.reserve(_threadsNum);
}

ThreadPool::~ThreadPool() {
    if (!_isExit) {
        stop();
    }
}

void ThreadPool::start() {
    for (size_t i = 0; i < _threadsNum; ++i) {
        _threads.emplace_back(new Thread(std::bind(&ThreadPool::doTask, this)));
        _threads[i]->start();
    }
}

void ThreadPool::addTask(TaskQueue::ElemType &&taskCallback) {
    _taskQueue.push(std::move(taskCallback));
}

void ThreadPool::stop() {
    while (!_taskQueue.empty()) {
        sleep(1);
    }
    _isExit = true;
    _taskQueue.wakeUp();
    for (auto &pThread : _threads) {
        pThread->join();
    }
}

void ThreadPool::doTask() {
    while (!_isExit) {
        TaskQueue::ElemType taskCallback = _taskQueue.pop();
        if (taskCallback) {
            taskCallback();
        }
    }
}
} // end of namespace myNameSpace
